package com.wxxymakers.cklabrecruit.controller;

import com.wxxymakers.cklabrecruit.entity.EmailRecord;
import com.wxxymakers.cklabrecruit.entity.EmailReturn;
import com.wxxymakers.cklabrecruit.entity.EmailTemplate;
import com.wxxymakers.cklabrecruit.entity.RegisterInfo;
import com.wxxymakers.cklabrecruit.entity.enum_.RegStatus;
import com.wxxymakers.cklabrecruit.service.EmailReturnService;
import com.wxxymakers.cklabrecruit.service.EmailTemplateService;
import com.wxxymakers.cklabrecruit.service.RegisterInfoService;
import com.wxxymakers.cklabrecruit.utils.EmailUtils;
import com.wxxymakers.cklabrecruit.utils.RestResponse;
import com.wxxymakers.cklabrecruit.utils.Utils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @AUTHOR soft
 * @DATE 2018/11/24 1:57
 * @DESCRIBE 邮件相关控制器
 */
@RestController
@RequestMapping("/email")
@RequiresRoles("admin")
public class EmailController {

    private final EmailUtils emailUtils;

    private final RegisterInfoService infoService;

    private final EmailTemplateService templateService;

    private final EmailReturnService emailReturnService;

    @Autowired
    public EmailController(EmailTemplateService templateService, RegisterInfoService infoService, EmailUtils emailUtils, EmailReturnService emailReturnService) {
        this.templateService = templateService;
        this.infoService = infoService;
        this.emailUtils = emailUtils;
        this.emailReturnService = emailReturnService;
    }

    /**
     * 发送邮件 同时保存未保存的模板
     * @param status 接收者状态
     * @param template 邮件模板
     */
    @PostMapping("/send")
    public RestResponse send(@RequestParam RegStatus status,
                             EmailTemplate template,
                             HttpServletRequest request) {
        String url = request.getRequestURL().toString();
        String host = url.substring(0, url.indexOf("/", 8));

        if (template == null) {
            return RestResponse.fail("模板不存在不能发送！");
        }
        templateService.saveAndUpdate(template);  // 将模板保存一下
        List<RegisterInfo> infos = infoService.getAll(new RegisterInfo(status));
        if (!CollectionUtils.isEmpty(infos)){
            EmailRecord record = templateService.addRecord(new EmailRecord(template.getId(), template.getTitle(),
                    status, infos.size(), template.getContent()));// 保存发送记录
            infos.forEach(info -> {
                EmailReturn emailReturn = new EmailReturn();
                emailReturn.setRegId(info.getId());
                emailReturn.setRecordId(record.getId());
                emailReturnService.add(emailReturn); // 添加一个无反馈的记录

                String returnUrl = host + "/email/return/t/" + Utils.tos(info.getId(), record.getId());
                emailUtils.send(template.getTitle(), template.getSendFrom(),
                        info.getEmail(), emailUtils.getRealEmail(template.getContent(), info, returnUrl));
            });

            return RestResponse.ok("邮件发送成功！");
        }
        return RestResponse.fail("没有发现合适的发送对象！");
    }

    /**
     * 保存或更新模板 对于同标题和有id的模板进行更新
     * @param template 模板信息
     */
    @PostMapping("/save")
    public RestResponse save(EmailTemplate template) {
        if (template == null || template.isEmpty()) return RestResponse.fail("模板内容不能为空！");
        if (template.getId() != null && template.getId() > 0) {
            return this.change(template);
        }
        EmailTemplate emailTemplate = templateService.saveAndUpdate(template);
        if (emailTemplate != null) {
            return RestResponse.ok(emailTemplate);
        }
        return RestResponse.fail("邮件模板保存失败！");
    }

    /**
     * 删除邮件模板
     * @param id id
     */
    @PostMapping("/delete/{id}")
    public RestResponse delete(@PathVariable Integer id) {
        EmailTemplate template = templateService.delete(id);
        if (template != null) {
            return RestResponse.ok(template);
        }
        return RestResponse.fail("删除失败！");
    }

    /**
     * 修改邮件模板
     * @param template 修改
     */
    @PostMapping("/change")
    public RestResponse change(EmailTemplate template) {
        if (templateService.change(template)) {
            return RestResponse.ok();
        }
        return RestResponse.fail("修改失败！");
    }

    /**
     * 根据id获取模板
     * @param id id
     */
    @PostMapping("/get/{id}")
    public RestResponse one(@PathVariable Integer id) {
        EmailTemplate one = templateService.getOne(id);
        if (null != one) {
            return RestResponse.ok(one);
        }
        return RestResponse.fail("获取失败！");
    }

    @PostMapping("/page")
    public RestResponse page(@RequestParam Integer pageNum,
                             @RequestParam Integer size,
                             EmailTemplate template) {
        Page<EmailTemplate> page = templateService.getPage(pageNum, size, template);
        if (page != null) {
            return RestResponse.ok(page);
        }
        return RestResponse.fail();
    }
}
